// pages/sales/my_mall/goods_list.js
var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var posterHandle = require("../../template/poster_handle.js");
var app = getApp();
Page(Object.assign({}, posterHandle, baseHandle,{

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    employee: wx.getStorageSync('employee'),
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    downLoadResPath: cf.config.downLoadResPath,
    downLoadUploadPath: cf.config.downLoadUploadPath,
    list: [],
    isLoading: false,
    pageSize: 10,
    curPage: 1,
    isBottom: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var ctx = this;
    app.getUserInfo(ctx, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      ctx.findGoodsList();
    });
  },
  findGoodsList(){
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    ctx.setData({ isLoading: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/goodsNew/findGoodsList",
      data: {
        cusmallToken: cusmallToken,
        calculateEmpCms:true,
        start: (ctx.data.curPage - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.result;
          if(list && list.length > 0){
            for(var i=0;i<list.length;i++){
              var item = list[i];
              if (item.calculateEmpCommission){
                item.calculateEmpCommission = JSON.parse(item.calculateEmpCommission);
              }
            }
          }
          ctx.setData({
            list: ctx.data.list.concat(list),
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else {
          wx.showToast({
            title: data.msg,
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({ isLoading: false });
        // ctx.drawPoster();
      }
    });
  },
  getSelfQRcode(e){
    var ctx = this;
    let goods = ctx.data.list[e.currentTarget.dataset.idx];
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/distributor/genGoodsPoster",
      data: {
        cusmallToken: cusmallToken,
        needBgPic:false,
        page: "pages/shopping_mall/detail/detail",
        goodsId: goods.id,
        eid: ctx.data.employee.id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          goods.goodsQrcode = data.model.qrcodeUrl + "?roundPic/radius/150";
          // ctx.drawPoster(goods);
          ctx.getPosterUrl(goods.id);
        } else {
          wx.showToast({
            title: data.msg,
          })
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  getPosterUrl: function (goodsId) {
    let that = this;
    let goodsPage = "pages/shopping_mall/detail/detail";
    wx.showLoading({
      title: '生成中...',
    });
    var postData = {
      cusmallToken: cusmallToken,
      page: goodsPage,
      eid: that.data.employee.id,
      goodsId: goodsId || that.data.id
    };
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/distributor/genGoodsPoster',
      data: postData,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        let data = res.data;
        console.log("data:", data)
        wx.hideLoading();
        if (data && 0 == data.ret && data.model.qrcodeUrl) {
          // that.setData({
          //   posterUrl: data.model.qrcodeUrl
          // });
          wx.previewImage({
            current: data.model.qrcodeUrl, // 当前显示图片的http链接
            urls: [data.model.qrcodeUrl] // 需要预览的图片http链接列表
          });
        }
      }
    })
  },
  // drawPoster(goods){
  //   let _this = this;
  //   let ctx = wx.createCanvasContext('goodsCanvas');
  //   let pxRatio = wx.getSystemInfoSync().screenWidth / 750;
  //   pxRatio *= 2;
  //   let bg = _this.data.downLoadResPath + "/huiketui/mobile/image/sales/goods_bg.png";
  //   let canvasWidth = 600 * pxRatio, canvasHeight = 1014 * pxRatio;
  //   let drawEle = [
  //     //背景
  //     { type: "img", x: 0, y: 0, width: canvasWidth, height: canvasHeight, url: bg },
  //     { type: "img", x: 0, y: 0, width: canvasWidth, height: canvasWidth, url: _this.data.downLoadUploadPath + goods.thumbnail },
  //     { type: "txt", x: 30 * pxRatio, y: 650 * pxRatio, fontSize: 30 * pxRatio, color: "#333", text: goods.name },
  //     { type: "txt", x: 20 * pxRatio, y: 735 * pxRatio, fontSize: 55 * pxRatio, color: "#f75d46", text: "￥"+(goods.price/100).toFixed(2) },
  //     { type: "txt", x: 220 * pxRatio, y: 735 * pxRatio, fontSize: 26 * pxRatio, color: "#888", text: "原价：" + (goods.price / 100).toFixed(2) },
  //     { type: "img", x: 48, y: 798, width: 175 * pxRatio, height: 175 * pxRatio, url: goods.goodsQrcode },
  //   ];
  //   wx.showLoading({
  //     title: '海报生成中...',
  //   });
  //   _this.drawPostDetailCommon(ctx, drawEle, 0, canvasWidth, canvasHeight, function () {
  //     wx.hideLoading();
  //     wx.canvasToTempFilePath({
  //       canvasId: 'goodsCanvas',
  //       success: function (res) {
  //         _this.setData({ posterUrl: res.tempFilePath });

  //         _this.previewImage(res.tempFilePath);
  //       }
  //     });
  //   });
  // },
  previewImage: function (imgUrl) {//预览海报图片
    wx.previewImage({
      current: imgUrl, // 当前显示图片的http链接
      urls: [imgUrl] // 需要预览的图片http链接列表
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var ctx = this;
    ctx.setData({
      list:[],
      isLoading:false,
      curPage:1,
      isBottom:false,
    });
    ctx.findGoodsList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var ctx = this;
    if (!ctx.data.isLoading) {
      ctx.setData({ curPage: ctx.data.curPage + 1 });
      ctx.findGoodsList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))